package com.xzx.springbootredis.controller;

import com.xzx.springbootredis.entity.Goods;
import com.xzx.springbootredis.service.GoodsService;
import com.xzx.springbootredis.utils.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("api/goods")
public class GoodsController {
    private final GoodsService goodsService;

    public GoodsController(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @PostMapping("add")
    public JsonResult addGoods(
            @RequestPart Goods goods,
            @RequestPart("mainImage") MultipartFile mainImage
    ) throws Exception {
        return goodsService.addGoods(goods, mainImage);
    }

    @GetMapping("list")
    public JsonResult getGoodsList(){
        List<Goods> goodsList = goodsService.getOnSaleGoodsOrderBySales();
        return JsonResult.success("查询成功", goodsList);
    }

    @GetMapping("detail")
    public JsonResult getGoodsDetail(@RequestParam("id") Long id) {
        Goods goods = goodsService.getGoodsById(id);
        if (goods == null || goods.getStatus() != 1) {
            return JsonResult.failed("商品不存在或已下架");
        }
        return JsonResult.success("查询成功", goods);
    }
}